﻿using Cysharp.Threading.Tasks;
using Net.Share;
using WordGames.System;

namespace WordGames
{
    internal class Main : IProcedure
    {
        readonly List<TcpNetwork> clients;

        public Main(TcpNetwork client)
        {
            clients = new List<TcpNetwork>() { client };
            client.RpcAdapter.AddRpc(this);
        }

        public Main(List<TcpNetwork> clients)
        {
            this.clients = new List<TcpNetwork>(clients);
            for (int i = 0; i < clients.Count; i++)
            {
                clients[i].RpcAdapter.AddRpc(this);
            }
        }

        public async UniTask Execute(TcpNetwork client)
        {
            Console.WriteLine("1.背包");
            Console.WriteLine("2.个人中心");
            Console.WriteLine("3.修炼");
            Console.WriteLine("4.设置");
            Console.WriteLine("5.聊天");
            var command = Console.ReadLine();
            if (command.StartsWith("5"))
            {
                Console.Write("请输入聊天内容:");
                var msg = Console.ReadLine();
                client.Call(ProtoType.WorldChat, msg);
            }
        }

        public async UniTask Execute(List<TcpNetwork> clients)
        {
            Console.WriteLine("1.背包");
            Console.WriteLine("2.个人中心");
            Console.WriteLine("3.修炼");
            Console.WriteLine("4.设置");
            Console.WriteLine("5.聊天");
            var command = Console.ReadLine();
            if (command.StartsWith("5"))
            {
                var args = command.Split(' ');
                clients[RandomHelper.Range(0, clients.Count)].Call(ProtoType.WorldChat, args[1]);
            }
        }

        [Rpc(NetCmd.SafeCallHash, ProtoType.WorldChat)]
        private void WorldChat(TcpNetwork self, string name, string message)
        {
            Console.WriteLine($"玩家{self.Name}收到聊天内容:[{name} {message}]");
        }

        [Rpc(NetCmd.SafeCallHash, ProtoType.SignOut)]
        private void SignOut(TcpNetwork self, string name)
        {
            Console.WriteLine($"玩家:{name} 在其他地方登录!");
            self.RpcAdapter.RemoveRpc(this);
            clients.Remove(self);
            if (clients.Count <= 0)
                ProcedureManager.Instance.procedure = new Login();
        }
    }
}